English 中文(简体)
为什么在创建之后立即将这一名骑士叫?
原标题:Why is this destructor being called immediately after creation?

我有以下几类:

class FixedByteStream {
public:
FixedByteStream() : size(0), address(NULL), existing(false) {}
FixedByteStream(int length) : existing(false) {
    size = length;
    address = new char[length];
}
FixedByteStream(int length, char* addr) : existing(true) {
    size = length;
    address = addr;
}
FixedByteStream(string* str, bool includeNull = false) : existing(true) {
    size = (*str).length();
    address = const_cast<char*>((*str).c_str());
    if (includeNull){
        ++size;
    }
}
~FixedByteStream() {
    if (existing == false) {
        delete [] address;
    }
    address = NULL;
}
int getLength() {
    return size;
}
char* getAddressAt(int index) {
    return &(address[index]);
}


char& operator[] (const int index) {
    return address[index];
}
operator char*() {
    return address;
}

private:
    bool existing;
    int size;
    char* address;
};

能够产生问题的非常简单检验:

FixedByteStream received;
received = FixedByteStream(12);
received[0] =  t ;

Valgrind warns about an invalid write, and debugging has shown why. FixedByteStream received; calls the constructor with no arguments (which is kind of stupid because it can t do anything). received = FixedByteStream(12); calls the constructor with the integer argument... and then immediately calls the destructor on itself, invalidating the object. It still works for some reason, but I d rather it not be placed in such an odd predicament that throws warnings.

因此,为什么有人叫它呢? 我可以理解的是,如果叫到“first,去除无用的暂时物体(而不是需要),那么,我就几乎在任何地方都使用了这种宣布为现在的签字模式,而且以前从未有过这样的问题。

最佳回答

您失踪的是指派操作员。 参看rule of three (或 5)。

问题大致如下:

T t; // default constructed t
t = T(2); // T(2) constructor with a single argument, assignment operator= called with this == &t

您不提供派任操作员,因此,临时的点值被简单地复制为拖车,然后在临时代行人中标明的记忆被删除。

Also: Don t have a default constructor, if the object constructed is invalid.

问题回答

If you object has any user defined constructor it is always constructed using a constructor. Just defining an object without any constructor arguments uses the default constructor independent of whether the object is being overwritten afterwards. That is

FixedByteStream received;

将打电话给违约建筑商。 下面的行文更令人感兴趣:

received = FixedByteStream(12);

This line create a temporary FixedByteStream with the argument 12. Internally this will allocate some memory but since temporaries are destroyed at the end of the full expression (in this case essentially when the semicolon is reached) that won t you do much good. Once this temporary object is constructed it is assigned to received using the automatically generated copy assignment which would look something like this if you d write it manually:

FixedByteStream& FixedByteStream::operator= (FixedByteStream& other) {
    this->existing = other.existing;
    this->size     = other.size;
    this->address  = other.address;
    return *this;
}

That is, once this assignment is executed, you have to identical copies of FixedByteStream, one of which is about to be destroyed and will release the resources just allocated. This is clearly not what you want, i.e. you definitely need to implement the copy assignment operator to make your class well-behaved. In general, the presence of a destructor which does anything interesting is a good hint at the fact that you ll need an assignment operator as well. In fact, there is another one of the generated operations, namely the copy constructor, which does roughly what the copy assignment does except that it copy constructs the members instead of assigning them. This is also not what you want with your class.

现在这个令人感兴趣的问题是:如何使用<代码>。 固定标签。 有效地来说,你要么需要使用参考计数,以跟踪目前有多少物体正在研究<代码>。 固定目录,分配内容的复印件,或需要使用移动自学支持(参考书目),这种支持只在C++2011年提供。 除非你真正知道你正在做些什么,否则我就建议在所有案件中复制这一流,并在以后采用更先进的办法。

一步步:

//create a new object using the default constructor
//I don t see why you think it s stupid that the constructor is called
//it s doing what you re telling it to do
FixedByteStream received;

//FixedByteStream(12) creates a temporary object
//you then copy this object in the received object you already have
//you re using the default operator =
//the temporary object is deleted after it is copied to received
received = FixedByteStream(12);

//received is a valid object
received[0] =  t ;

EDIT:

我看到,对这一问题的答复有很多。 对此,我可能会产生一些仇恨,但这是一个极其重要的概念,我对此表示反对,以便错误的答案不会被接受和放弃。

你基本上把一些物体放在 st头上。

我简化了你的案件:

class A
{
    A() {}
    A(const A& other) {}
    A& operator = (const A& other) {}
};

Let s talk about scope:

{ //begin scope
  A a;  //object a is created here
        //default constructor is called
} //a is destroyed here
  //destructor is called

迄今情况良好。

现职:

{
   //two objects are created with default constructor
   A a;
   A b;
   //object b is assigned to a
   //operator = will be called
   //both objects are still alive here
   a = b;
   //...
} // a and b will be destroyed, destructor called

最后部分:

{
   A a;
   a = A();
}

基本相当于:

{
   A a;
   {
      A b;
      a = b;
   }
}

当您打电话a = A(),A(> 创建临时物体,被分配到a,然后予以销毁。

因此,我的简化中标的<代码>b是被销毁的临时物体。 页: 1

Not the assignment operator declaration. If you don t define one, a default is used. You probably want to write your own in this case.

<编码> 固定ByteStream(12) 分配给<编码>接收。 通过违约操作人=。 通知:你通过使用<代码>新在座标上拨打<代码>FixedByteStream(12),但在地方范围分配该代码时,没有具体说明可持有的变量的名称。

你的法典与:

FixedByteStream received;
FixedByteStream temp(12);
received = temp;
received[0] =  t ;

只有在我的例子中,<代码>temp有一个名称及其范围是整个功能,在你的测试代码<代码>temp。 没有名字,只存在一条线,然后销毁。

The FixedByteStream(12) Object You ve caused not be used after this line,因为它甚至连一个名词。

已在这一行文上提出反对。

FixedByteStream received;

页: 1

received = FixedByteStream(12);

你重新开始。 这样做的正确方法是:

FixedByteStream received(12);
// Or
FixedByteStream *received;
received = new FixedByteStream(12);

(一) 无限期停留在先

似乎你不理解物体生命周期,错误地将这一守则解释为 Java。

当你写“FixedByteStream”时;使用无标记构造制造的固定标签。 当你写<条码>收到后 = 固定ByteStream(12);制造另一个物体时,=操作者被打电话,新制造的物体被拆除。

并且,你没有压倒一切的经营者,因此该物体是用tes复制的,这是不正确的。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?