静态内存分配中的浅复制构造函数问题?

时间:2015-07-29 15:35:58

标签: c++ oop memory memory-management

浅拷贝: When we initalize one object with another then the compiler copies state of one object to the other using copy constructor by assigning data member values of previous object to newly created object.

浅拷贝问题

  • 悬空指针(指向不正确的内存位置的指针)。
  • 更新该内存位置的数据。

在复制构造函数two objects中指向相同的memory location,然后可以发生上述两个问题。我研究过这两个问题发生在memory is allocated dynamically时。如果不涉及dynamic memory那么它可以正常工作。

问题: 我的问题是在编译时是否将静态内存分配给对象,并且在运行时通过执行某些事件来初始化已经静态分配了内存的该对象的另一个对象。那么也会有同样的问题吗?如果不是为什么以及如何?内存位置与两个对象指向的位置相同。那么为什么不会出现Dangling Pointer问题。

2 个答案:

答案 0 :(得分:1)

  

我的问题是在编译时是否将静态内存分配给对象,并且在运行时通过执行某些事件来初始化该对象中已经静态分配了内存的另一个对象。那么也会有同样的问题吗?如果不是为什么以及如何?

你将有两个指针指向同一个实例的对象,因此两者都将修改同一个对象。动态内存分配的问题是它必须在某个时刻释放,所以如果一个对象释放它,那么第二个将释放已经释放的内存 - 这是未定义的行为。所以对于静态对象的情况,“悬空指针”没有问题,因为你无法释放它的内存(也就是不应该尝试),所以你不会有UB。

答案 1 :(得分:1)

  

在复制构造函数中,两个对象指向相同的内存位置,然后可以发生上述两个问题。我研究过,当动态分配内存时会发生这两个问题。如果不涉及动态内存,那么它可以正常工作。

这并不严格(尽管这是一个罕见的问题):

#include <iostream>

using namespace std;

class Example
{
public:
    Example(int * const in) : p{in} {}

    int value() const { return *p; }
    int value(const int v) const { *p = v; return *p; }

private:
    int * p;
};

static int a = 5;
static Example first{&a};
// `first` now holds a pointer to `a`
static Example second = first;
// Now `first` and `second` hold pointers to the same static memory

int main()
{
    // Outputs `true`
    cout << boolalpha << (first.value() == second.value()) << endl;

    first.value(7);

    // Because they point to the same memory, this will output `true`
    cout << boolalpha << (first.value() == second.value()) << endl;
}
  

我的问题是在编译时是否将静态内存分配给对象,并且在运行时通过执行某些事件来初始化该对象中已经静态分配了内存的另一个对象。那么也会有同样的问题吗?如果不是为什么以及如何?

你仍然会遇到同样的问题

  

更新该内存位置的数据。

#include <iostream>

using namespace std;

class Example
{
public:
    Example(int * const in) : p{in} {}

    int value() const { return *p; }
    int value(const int v) const { *p = v; return *p; }

private:
    int * p;
};

static int a = 5;
static Example first{&a};
// `first` now holds a pointer to `a`

int main()
{
    Example * second = new Example(first); // implicit copy constructor
    // Now `first` and `second` hold pointers to the same static memory,
    // though `second` is allocated dynamically

    // Outputs `true`
    cout << boolalpha << (first.value() == second->value()) << endl;

    first.value(7);

    // Because they point to the same memory, this will still output `true`
    cout << boolalpha << (first.value() == second->value()) << endl;
}