Thread: Ban pointers or references on classes?

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by CornedBee View Post
    Seriously, though, the fact that the critical section is affected by the smart pointers constness indicates that you have one per smart pointer. Is that true? If it is, that's completely useless. Allocate a CCriticalSection next to your reference count, because like it, it must be shared among all instances that refer to the same pointer.
    Once you've done that, constness will no longer be a problem.
    There are two problems here:
    A critical section is needed to make sure to two or more threads use the same smart pointer class at once (references via threads, anyone?). Unless, of course, I can remove that practice. Two threads should NOT use the same smart class pointer.
    Code:
    // Let's just assume for simplicity's sake that main calls both thread1 and thread2 in different threads.
    void thread1(pp<int>& pTest)
    {
    	int n = *pTest; // BAD!
    }
    void thread2(pp<int> pTest)
    {
    	int n = *pTest; // Good, because it's not the same smart pointer
    }
    int main()
    {
    	ppnew<int> p = 0;
    	thread1(p);
    	thread2(p);
    }
    Also, the thread affinity test should be done whether the pointer is thread-safe or not, because just because you can have more than one pointer to the same object on different threads, still doesn't mean you may use any single pointer on more than one thread at the same time. That's still dangerous.
    I guess that answers my question about the above reference count, huh? I'll make some changes.

  2. #2
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    I should probably pass it by const reference, but it seems I can't get the class to work with const since the locking and unlocking fails if the functions are const (go figure?).
    Why not define your mutexes to be mutable?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointers v References
    By m37h0d in forum C++ Programming
    Replies: 28
    Last Post: 06-30-2008, 01:29 PM
  2. Replies: 12
    Last Post: 12-31-2007, 06:59 AM
  3. Pointers, Classes, and Errors o my!
    By Scottc1988 in forum C++ Programming
    Replies: 12
    Last Post: 03-13-2003, 10:14 PM
  4. Pointers to derived classes.
    By sean in forum C++ Programming
    Replies: 3
    Last Post: 11-13-2001, 08:19 PM
  5. Pointers to inherited classes
    By sean in forum C++ Programming
    Replies: 1
    Last Post: 11-03-2001, 03:04 PM