use_count becomes -1 when using shared_ptr in C++

末鹿安然 提交于 2019-12-11 15:50:27

问题


GenericStack.h

#ifndef _GENERIC_STACK_TROFIMOV_H_
#define _GENERIC_STACK_TROFIMOV_H_

#include <memory>

class GenericStack {
    struct StackNode {
        std::shared_ptr<void> _data; 
        StackNode* _next;
        StackNode(const std::shared_ptr<void>& p, StackNode* next) 
            : _data(p), _next(next) {

        }
    };
    StackNode* _top; 

    GenericStack(const GenericStack&);
    GenericStack& operator=(const GenericStack&);

protected:
    GenericStack();
    ~GenericStack();
    void push(const std::shared_ptr<void>&);
    void pop();
    std::shared_ptr<void>& top();
    bool isEmpty() const;

public:
    class EmptyError {
        const char* _message;
    public:
        EmptyError(const char* message)
            : _message(message) {

        }
        const char* getMessage() const {
            return _message;
        }
    };
};

template <class T>
class TStack: private GenericStack {                  
public:
    void push(const std::shared_ptr<T>& p) { GenericStack::push(p); }
    void pop() { GenericStack::pop(); }
    std::shared_ptr<T>& top() { return std::static_pointer_cast<T>(GenericStack::top()); }
    bool isEmpty() const { return GenericStack::isEmpty(); }
};

#endif

GenerickStack.cpp

#include "GenericStack.h"

GenericStack::GenericStack()
    : _top(0) {

};
GenericStack::~GenericStack() {
    while(!isEmpty()) {
        pop();
    }
};

void GenericStack::push(const std::shared_ptr<void>& p) {
    _top = new StackNode(p, _top);
}

std::shared_ptr<void>& GenericStack::top() {
    if(isEmpty()) {
        throw EmptyError("No more elements in stack.");
    }
    return _top->_data;
}
void GenericStack::pop() {
    if(isEmpty()) {
        throw EmptyError("No more elements in stack.");
    }

    StackNode* t = _top->_next;
    delete _top;
    _top = t;
}

bool GenericStack::isEmpty() const {
    return !_top;
}

Main.cpp

#include <iostream>
#include "GenericStack.h"
//#define NDEBUG
#include <assert.h>

void ordinaryUsageVerification() {
    TStack<int> intStack;

    {
        std::shared_ptr<int> sh(new int(7));
        intStack.push(sh);
        intStack.isEmpty();
        assert(!intStack.isEmpty() && sh.use_count() == 2);
    }
    //assert(!intStack.isEmpty() && intStack.top().use_count() == 1);
    std::cout << "intStack.top().use_count(): " << intStack.top().use_count() << std::endl;

    std::cout << "*gs.top(): " << *intStack.top() << std::endl;
    intStack.pop();
    assert(intStack.isEmpty());
}


int main() {
    ordinaryUsageVerification();

    return 0;
}

After the following two line in Main.cpp:

std::shared_ptr<int> sh(new int(7));
intStack.push(sh);

I am expecting intStack.top().use_count() to be equal 2, but it is equal -1.

I am expecting such a behavior because when calling a push method I am passing the shared_ptr by reference, so the use_count should not change. And only in one place in GenericaStack.h here:

StackNode(const std::shared_ptr<void>& p, StackNode* next) 
            : _data(p), _next(next) {

The use_count increments by one for p.

So, given that before push I had sh.use_count() == 1 and after intStack.push(sh); I had sh.use_count() == 2 I should get intStack.top().use_count() == 2, but what I am getting is intStack.top().use_count() == -1. Why?

Thank you.

After modifying GenericStack.h in this way:

#ifndef _GENERIC_STACK_TROFIMOV_H_
#define _GENERIC_STACK_TROFIMOV_H_

#include <memory>

class GenericStack {
    struct StackNode {
        std::shared_ptr<void> _data; 
        StackNode* _next;
        StackNode(std::shared_ptr<void>& p, StackNode* next) 
            : _data(p), _next(next) {

        }
    };
    StackNode* _top; 

    GenericStack(const GenericStack&);
    GenericStack& operator=(const GenericStack&);

protected:
    GenericStack();
    ~GenericStack();
    void push(std::shared_ptr<void>&);
    void pop();
    std::shared_ptr<void>& top();
    bool isEmpty() const;

public:
    class EmptyError {
        const char* _message;
    public:
        EmptyError(const char* message)
            : _message(message) {

        }
        const char* getMessage() const {
            return _message;
        }
    };
};

template <class T>
class TStack: private GenericStack {                  
public:
    void push(std::shared_ptr<T>& p) { 
        GenericStack::push(p); 
    }
    void pop() { GenericStack::pop(); }
    std::shared_ptr<T> top() { return std::static_pointer_cast<T>(GenericStack::top()); }
    bool isEmpty() const { return GenericStack::isEmpty(); }
};

#endif

I am getting an error:

Error 1 error C2664: 'GenericStack::push' : cannot convert parameter 1 from 'std::shared_ptr<_Ty>' to 'std::shared_ptr<_Ty> &' ...\stack\genericstack.h 47 Stack

It is about this part:

void push(std::shared_ptr<T>& p) { 
    GenericStack::push(p); 
}

回答1:


Let's review the specification of std::static_pointer_cast: std::static_pointer_cast() returns an rvalue, a.k.a. a temporary object.

std::shared_ptr<T>& top() { return std::static_pointer_cast<T>(GenericStack::top()); }

This returns a reference to a temporary object that gets destroyed by the time this top() returns. Undefined behavior. Most modern C++ compilers are generally capable of detecting this common instance of undefined behavior, and your compiler should be barking at you, on this line.

In general, attempts to defeat C++'s type-safety, by casting things back and forth from a void * (the apparent underlying purpose of this set of templates) -- that never ends well.



来源:https://stackoverflow.com/questions/53467462/use-count-becomes-1-when-using-shared-ptr-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!